<template>
  <div>
    <el-dialog
      v-model="_dialogVisible"
      :title="`分配权限（${title}）`"
      :before-close="handleClose"
      destroy-on-close
      draggable
    >
      <el-tree
        ref="treeRef"
        :data="menuData"
        show-checkbox
        node-key="menu_id"
        default-expand-all
        :expand-on-click-node="false"
        :props="{
          label: 'menu_name',
          children: 'children',
          class: nodeLeftClass,
        }"
        :highlight-current="true"
        :check-on-click-node="true"
        :default-checked-keys="defaultCheckedKeys"
      />
      <template #footer>
        <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
        <el-button @click="handleClose">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { VoListItem } from '@/api/auth/model/ruleModel'
import { getRuleVoList } from '@/api/auth/rule'
import HandleTree from '@/utils/tree'
import { getMenuId, assignPermissions } from '@/api/auth/role'

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
  },
  role_id: {
    type: Number,
    default: 0,
  },
  title: {
    type: String,
    default: '',
  },
})

const emit = defineEmits(['update:dialogVisible'])
const _dialogVisible = ref<boolean>(false)

let menuData = ref<VoListItem[]>([])
const defaultCheckedKeys = ref<number[]>([])
const treeRef = ref<any>(null)

watch(
  () => props.dialogVisible,
  () => {
    getMenuVoList()
    _dialogVisible.value = props.dialogVisible
  }
)

watch(
  () => _dialogVisible.value,
  () => {
    emit('update:dialogVisible', _dialogVisible.value)
  }
)

watch(
  () => [props.role_id, props.dialogVisible],
  () => {
    props.dialogVisible && props.role_id && getCheckedMenu()
  }
)

const nodeLeftClass = (data: any) => {
  if (!data.children) {
    return 'float-left'
  }
  return ''
}

const getMenuVoList = async () => {
  if (props.dialogVisible) {
    const { code, data, message } = await getRuleVoList()
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    menuData.value = HandleTree.handleTree(
      data,
      'menu_id',
      'parent_id',
      'children'
    )
  }
}

const getCheckedMenu = async () => {
  if (props.role_id) {
    const { code, data, message } = await getMenuId({ role_id: props.role_id })
    if (code != 200) {
      ElMessage.error(message)
      return
    }
    defaultCheckedKeys.value = (data ?? []).map((item) => item.menu_id)
  }
}

const handleClose = () => {
  _dialogVisible.value = false
}

const handleSubmit = async () => {
  const keys = [
    ...treeRef.value.getCheckedKeys(),
    ...treeRef.value.getHalfCheckedKeys(),
  ]
  const { code, message } = await assignPermissions({
    role_id: props.role_id,
    menu_ids: keys,
  })
  if (code != 200) {
    ElMessage.error(message)
    return
  }
  handleClose()
  ElMessage.success(`权限分配成功`)
}
</script>

<style scoped></style>
